﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq.Expressions;

namespace Idlesoft.Utils
{
	public static class MiscExtensions
	{
		public static IEnumerable<TItem> MakeEnumerable<TItem>(this TItem item) { return item.MakeArray(); }
		public static TItem[] MakeArray<TItem>(this TItem item) { return new TItem[] { item }; }
		public static List<TItem> MakeList<TItem>(this TItem item) { return new List<TItem>(item.MakeArray() ); }

		public static string FileFriendly(this DateTime dt, string pattern = "{0:yyyy_MM_dd-hh.mm.ss.tt}")
		{
			return string.Format(pattern, dt);
		}

		public static int MyDepth<TClass>(this TClass self)
		{
			return Common.Depth(self.GetType());
		}

		public static Dictionary<TValue, TKey> Invert<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
		{
			Dictionary<TValue, TKey> inverted = null;
			if (null != dictionary)
			{
				inverted = new Dictionary<TValue, TKey>();
				foreach (var kvp in dictionary)
					inverted[kvp.Value] = kvp.Key;
			}
			return inverted;
		}

		public static string Chomp(this string text, string pattern = "[\r\n]|\n|\r")
		{
			return Regex.Replace(text, string.Format("({0})*($)", pattern), "");
		}

		#region safe invoke
		public static void SafeInvoke(this EventHandler handler, object sender)
		{
			if (handler != null)
				handler(sender, EventArgs.Empty);
		}
		public static void SafeInvoke<TItem>(this EventHandler<TItem> handler, object sender, TItem args)
			where TItem : EventArgs
		{
			if (handler != null)
				handler(sender, args);
		}
		#endregion safe invoke

		#region combinations
		public static bool AnyEquals<TItem>(this TItem item, IEnumerable<TItem> items)
		{
			return items.Any(i => i.Equals(item));
		}
		public static bool AllEquals<TItem>(this TItem item, IEnumerable<TItem> items)
		{
			return items.All(i => i.Equals(item));
		}
		#endregion combinations
	}
}
